//
//  AppController_SouceList.m
//  QuickTimeTest
//
//  Created by c on 09/01/30.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"
#import "SimpleTreeNode.h"
#import "ImageAndTextCell.h"

#define COLUMNID_NAME		 @"NameColumn"

@implementation AppController (SouceList)
//当前选中的项
- (SimpleTreeNode *)SelectedItem
{
	NSEnumerator *selectedRows = [outlineView selectedRowEnumerator];
    NSNumber *selRow = nil;
	if(selRow = [selectedRows nextObject])
	{
		if ([outlineView itemAtRow:[selRow integerValue]]) 
		{
			return [outlineView itemAtRow:[selRow integerValue]];
		}
	}
	return nil;
}

//单击响应事件
- (void)outlineViewSelectionDidChange:(NSNotification *)notification
{	
	SimpleTreeNode *node = [self SelectedItem];
	if(node == nil)
		return;
	SimpleNodeData *data = [node nodeData];
	NSString *path = [data path];
	int dictType = [data dictType];
//	NSLog(@"selected name : %@ ",nodeName);

	
//	if([nodeName isEqualToString:@"Music"])
//	{
//		NSString *parentNodeName = [[[node nodeParent] nodeData]name];
//		NSLog(@"selected name of parentNodeName : %@ ",parentNodeName);
//		if([parentNodeName isEqualToString:@"Device"])
//		{
//			//加载Device下的Music文件夹下所有音频文件（子文件夹不管）
//			NSFileManager *fileManager = [NSFileManager defaultManager];
//			NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:NULL];
//			for (NSString *stringTemp in fileList)
//			{
//				NSLog(stringTemp);
//			}
//			
//		}
//		else		//其他设备（不只一台设备与当前系统连接着）
//		{
//			//提取设备编号，规则是：	1	2	3	4	...
//		}
//	}
//	
//	if([nodeName isEqualToString:@"Movie"])
//	{
//		NSString *parentNodeName = [[[node nodeParent] nodeData]name];
//		NSLog(@"selected name of parentNodeName : %@ ",parentNodeName);
//		if([parentNodeName isEqualToString:@"Device"])
//		{
//			
//		}
//		else		//其他设备（不只一台设备与当前系统连接着）
//		{
//			//提取设备编号，规则是：	1	2	3	4	...
//		}
//	}
	
	
	
	
//	if([nodeName isEqualToString:@"Picture"])
//	{
//		NSString *parentNodeName = [[[node nodeParent] nodeData]name];
//		NSLog(@"selected name of parentNodeName : %@ ",parentNodeName);
//		if([parentNodeName isEqualToString:@"Device"])
//		{
//			
//		}
//		else		//其他设备（不只一台设备与当前系统连接着）
//		{
//			//提取设备编号，规则是：	1	2	3	4	...
//		}
//		
//		return;
//	}	
	
	//判断，若所选图标的目录不存在，则创建。
	//分情况，若是Library的，则创建
	//		 若是设备的，启动线程，每隔5秒钟，同步设备的文件夹，若是当前TableView的文件夹被删除，则跳到根目录，即Music或者Movie
	
	//加载Device下的Music文件夹下所有音频文件（子文件夹不管）
	if(currentPath != nil)
	{
		[currentPath release];
		currentPath = nil;
	}
	currentPath = [path retain];

	currentType = dictType;
	[self initTableViewWithPath:currentPath];
}



// ================================================================
//  NSOutlineView data source methods. (The required ones)
// ================================================================

// Required methods. These methods must handle the case of a "nil" item, which indicates the root item.
- (id)outlineView:(NSOutlineView *)ov child:(int)index ofItem:(id)item {
    SimpleTreeNode *node = (item == nil) ? treeData : item;
    return [node childAtIndex:index];
}

- (BOOL)outlineView:(NSOutlineView *)ov isItemExpandable:(id)item {
    SimpleTreeNode *node = (item == nil) ? treeData : item;
    return [[node nodeData] isGroup];
}

- (int)outlineView:(NSOutlineView *)ov numberOfChildrenOfItem:(id)item {
    SimpleTreeNode *node = (item == nil) ? treeData : item;
    return [node numberOfChildren];
}
/////////////////
- (BOOL)outlineView:(NSOutlineView *)ov shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item {
    return NO;
}
//////////////////


- (id)outlineView:(NSOutlineView *)ov objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
    id objectValue = nil;
    SimpleNodeData *data = [item nodeData];
    
    // The return value from this method is used to configure the state of the items cell via setObjectValue:
    if ((tableColumn == nil) || [[tableColumn identifier] isEqualToString:COLUMNID_NAME]) {
		objectValue = [data name];
    }    
    return objectValue;
}

// Optional method: needed to allow editing.
- (void)outlineView:(NSOutlineView *)ov setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item  {
    SimpleNodeData *data = [item nodeData];
    
    // Here, we manipulate the data stored in the node.
    if ((tableColumn == nil) || [[tableColumn identifier] isEqualToString:COLUMNID_NAME]) {
		[data setName:object];
    }	
}

// We can return a different cell for each row, if we want
- (NSCell *)outlineView:(NSOutlineView *)ov dataCellForTableColumn:(NSTableColumn *)tableColumn item:(id)item {
    return [tableColumn dataCell];
}

// To get the "group row" look, we implement this method.
- (BOOL)outlineView:ov isGroupItem:(id)item {
    return NO;//[[item nodeData] isGroup] && [useGroupRowLook state];
}

- (BOOL)outlineView:(NSOutlineView *)ov shouldExpandItem:(id)item {
    return [[item nodeData] isExpandable];
}

- (void)outlineView:(NSOutlineView *)ov willDisplayCell:(NSCell *)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item {    
    SimpleNodeData *data = [item nodeData];
    if ((tableColumn == nil) || [[tableColumn identifier] isEqualToString:COLUMNID_NAME]) {
        ImageAndTextCell *imageAndTextCell = (ImageAndTextCell *)cell;
		
		[imageAndTextCell setImage:[data iconRep]];
    }
}

- (BOOL)outlineView:(NSOutlineView *)ov shouldSelectItem:(id)item {
    // Control selection of a particular item. 
    return [[item nodeData] isSelectable];
}

// ================================================================
//  NSOutlineView data source methods. (dragging related)
// ================================================================
//////////////////////////////////////////////////////////////////////
- (NSDragOperation)outlineView:(NSOutlineView *)ov validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)childIndex {
    // This method validates whether or not the proposal is a valid one. Returns NO if the drop should not be allowed.
//	NSLog(@"validate Drop");
	if ([outlineView delegate]==nil)
	{
		return NSDragOperationNone;
	}
	
	if ([[[info draggingPasteboard] types] containsObject:NSFilenamesPboardType] || [[[info draggingPasteboard] types] containsObject:DragDropTableCellPboardType])
	{
		SimpleTreeNode *currentNode = item;
		if([[currentNode nodeData]isSelectable])
		{
			return NSDragOperationCopy;
		}
	}

	return NSDragOperationNone;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)childIndex {
	SimpleTreeNode *currentNode = item;
	
	int type = [[currentNode nodeData] dictType];
	NSString *toPath = [[currentNode nodeData] path];
	NSPasteboard *pboard;
	pboard = [info draggingPasteboard];
	// 如果拖入的是外部文件的话，做以下处理
	if ([[pboard types] containsObject:NSFilenamesPboardType])
	{
		NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
		NSArray *params = [[NSArray alloc]initWithObjects:filenames,[NSNumber numberWithInt:type],toPath,nil];
//		NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(copyFileThread:) object:[params retain]];
//		[myThread start];
		[NSThread detachNewThreadSelector:@selector(copyFileThread:) toTarget:self withObject:[params retain]];

		[params release];
		return YES;
	}
	// 如果拖入的是从TableView的行的话，做以下处理	
	if ([[pboard types] containsObject:DragDropTableCellPboardType])
	{
		NSData *data = [pboard dataForType:DragDropTableCellPboardType];
        NSIndexSet *rowIndexes = (NSIndexSet*)[NSKeyedUnarchiver unarchiveObjectWithData:data];
		unsigned index		= [rowIndexes lastIndex];
		NSMutableArray * filenames = [[NSMutableArray alloc]init];

		while(NSNotFound != index) {
			AMTFile *amtFile = [fileArray objectAtIndex:index];
			[filenames addObject:[amtFile path]];
			///
			index = [rowIndexes indexLessThanIndex:index];
		}
		
		NSArray *params = [[NSArray alloc]initWithObjects:filenames,[NSNumber numberWithInt:type],toPath,nil];
		[NSThread detachNewThreadSelector:@selector(copyFileThread:) toTarget:self withObject:[params retain]];

		[params release];
		return YES;
		
	}
		
	return NO;	
}


@end
